package com.cyf.plc.base

import android.content.Context
import android.os.Bundle
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.navigation.fragment.NavHostFragment
import androidx.viewbinding.ViewBinding
import com.cyf.library.util.UIUtils
import com.cyf.library.util.logi
import com.squareup.moshi.Moshi
import dagger.android.AndroidInjection
import io.github.inflationx.viewpump.ViewPumpContextWrapper
import org.greenrobot.eventbus.*
import javax.inject.Inject

abstract class BaseActivity<VM : ViewModel, VB : ViewBinding> : AppCompatActivity() {

    @Inject
    protected lateinit var mViewModelProvider: ViewModelProvider.Factory

    @Inject
    protected lateinit var moshi: Moshi

    protected val mViewModel by lazy { createViewModel() }

    protected lateinit var mViewBinding: VB

    override fun attachBaseContext(newBase: Context?) {
        super.attachBaseContext(newBase?.let { ViewPumpContextWrapper.wrap(it) })
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        AndroidInjection.inject(this)

        super.onCreate(savedInstanceState)

        mViewBinding = getViewBinding()

        setContentView(mViewBinding.root)

        if (!EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().register(this);
        }

        initView()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getEventBusException(eventBusException: EventBusException) {
        eventBusException.message?.logi()
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    fun getSubscriberExceptionEvent(subscriberExceptionEvent: SubscriberExceptionEvent) {

    }

    override fun onDestroy() {
        super.onDestroy()
        EventBus.getDefault().unregister(this)
    }

    abstract fun initView()

    abstract fun getViewBinding(): VB

    abstract fun createViewModel(): VM

    @Suppress("UNCHECKED_CAST")
    fun <F : Fragment> AppCompatActivity.getFragment(fragmentClass: Class<F>): F? {
        val navHostFragment = this.supportFragmentManager.fragments.first() as NavHostFragment

        ("Fragment Size:" + this.supportFragmentManager.fragments).logi()

        navHostFragment.childFragmentManager.fragments.forEach {
            if (fragmentClass.isAssignableFrom(it.javaClass)) {
                return it as F
            }
        }
        return null
    }

    override fun onBackPressed() {
        super.onBackPressed()
        ("Fragment Size:" + this.supportFragmentManager.fragments).logi()
    }

    override fun onStart() {
        super.onStart()
        UIUtils.hideNavigation(this)
    }

    override fun onStop() {
        super.onStop()
        UIUtils.hideNavigation(this)
    }
}